import 'package:amway_superapp_creator_plugin/analysis/zhuge_circle.dart';
import 'package:amway_superapp_creator_plugin/config/colors_config.dart';
import 'package:amway_superapp_creator_plugin/dialog/comm_tip_dialog.dart';

import 'package:amway_superapp_creator_plugin/models/circle_detail_model.dart';
import 'package:amway_superapp_creator_plugin/models/haowu_product_models.dart';
import 'package:amway_superapp_creator_plugin/routers/application.dart';
import 'package:amway_superapp_creator_plugin/routers/routes.dart';
import 'package:amway_superapp_creator_plugin/utils/oss_util.dart';
import 'package:amway_superapp_creator_plugin/utils/toast_util.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/circle/related_shop_model.dart';
import 'package:amway_superapp_creator_plugin/widget/diver.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:provider/provider.dart';
import 'package:amway_superapp_creator_plugin/viewmodels/base_model.dart';

class RelatedShop extends StatefulWidget {
  CircleDetailData circle;
  final setFocus;
  BoolCallBack back;

  RelatedShop(this.circle, {this.setFocus, this.back});

  @override
  _RelatedShopState createState() => _RelatedShopState();
}

class _RelatedShopState extends State<RelatedShop> {
  @override
  void initState() {
    super.initState();
    Provider.of<RelatedShopModel>(context, listen: false)
        .showShopData(widget.circle.products);
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<RelatedShopModel>(builder: (context, provide, child) {
      return Container(
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                    color: ColorsConfig.c_14000000,
                    offset: Offset(0.0, 0.0), //阴影xy轴偏移量
                    blurRadius: 12.0, //阴影模糊程度
                    spreadRadius: 0.0 //阴影扩散程度
                    )
              ]),
          margin: EdgeInsets.only(
              left: ScreenUtil().setWidth(15),
              right: ScreenUtil().setWidth(15),
              bottom: ScreenUtil().setHeight(15)),
          child: _shop(provide, context));
    });
  }

  /*
* 标题
* */
  Widget _title(RelatedShopModel provide, BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(15),
          top: ScreenUtil().setWidth(15),
          right: ScreenUtil().setWidth(15)),
      child: Row(
        children: [
          Text("关联商品",
              style: TextStyle(
                  fontSize: ScreenUtil().setSp(18),
                  color: ColorsConfig.c_2c2c2c,
                  fontWeight: FontWeight.bold)),
          Spacer(flex: 1),
          provide.shopList.length > 0
              ? MaterialButton(
                  height: ScreenUtil().setHeight(40),
                  color: ColorsConfig.c_396E75,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(25)),
                  onPressed: () {
                    ZhugeCircleAnalysis.circleAddGoods("编辑动态");
                    widget.setFocus();
                    if (provide.shopList.length == 50) {
                      ToastUtils.showShortToast("已达到数量上限");
                      return;
                    }
                    Map<String, dynamic> map = Map();
                    map['max'] = 50 - provide.shopList.length;
                    List<HaowuProduct> productList = [];
                    provide.shopList.forEach((element) {
                      productList.add(element);
                    });
                    map['items'] = productList;
                    Application.router
                        .navigateTo(context, Routes.shopCategory,
                            routeSettings: RouteSettings(arguments: map))
                        .then((value) {
                      if (value == null) {
                        return;
                      }
                      if (value is List<HaowuProduct>) {
                        if (provide.shopList.length != value.length) {
                          widget.back.call(true);
                        }
                      }
                      provide.setShop(value);
                    });
                  },
                  child: Text("添加",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: ScreenUtil().setSp(18))),
                )
              : Container()
        ],
      ),
    );
  }

  /*
  * 商品
  * */
  Widget _shop(RelatedShopModel provide, BuildContext context) {
    if (provide.shopList.isNotEmpty && provide.shopList.length > 0) {
      if (widget.circle.products != null && widget.circle.products.length > 0) {
        widget.circle.products.clear();
      } else {
        widget.circle.products = List<Products>();
      }
      provide.shopList.forEach((element) {
        if (element.priceData != null) {
          Products product = new Products(
              itemSku: element.itemSku,
              skuName: element.skuName,
              skuCode: element.skuCode,
              specDescription: element.specDescription,
              picture: element.picture,
              productName: element.productName,
              priceData: PriceData(
                  price: element.priceData.price,
                  skuCode: element.priceData.skuCode));
          widget.circle.products.add(product);
        }
      });
    }
    return Column(
      children: [
        _title(provide, context),
        provide.shopList.length > 0
            ? Container(
                margin: EdgeInsets.only(
                    top: ScreenUtil().setHeight(5),
                    bottom: ScreenUtil().setHeight(10),
                    left: ScreenUtil().setHeight(15),
                    right: ScreenUtil().setHeight(15)),
                child: Divider(
                    color: ColorsConfig.c_14000000,
                    height: ScreenUtil().setHeight(1)))
            : Container(),
        provide.shopList.length > 0
            ? ListView.builder(
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                //自适应高度
                padding: EdgeInsets.only(
                    left: ScreenUtil().setHeight(15),
                    right: ScreenUtil().setHeight(15),
                    bottom: ScreenUtil().setHeight(15)),
                itemCount: provide.shopList.length,
                itemBuilder: (context, index) {
                  return _shopItem(provide, index, context);
                },
              )
            : Container(
                padding: EdgeInsets.only(
                    left: ScreenUtil().setHeight(15),
                    right: ScreenUtil().setHeight(15),
                    bottom: ScreenUtil().setHeight(15)),
                child: Column(
                  children: [
                    // _title(provide, context),
                    InkWell(
                      focusColor: Colors.white,
                      child: Container(
                        child: Image.asset('picture/icon_add_related.png',
                            package: 'amway_superapp_creator_plugin'),
                        margin: EdgeInsets.only(top: 15),
                      ),
                      onTap: () {
                        ZhugeCircleAnalysis.circleAddGoods("编辑动态");
                        Map<String, dynamic> map = Map();
                        map['max'] = 50 - provide.shopList.length;
                        List<HaowuProduct> productList = [];
                        provide.shopList.forEach((element) {
                          productList.add(element);
                        });
                        map['items'] = productList;
                        Application.router
                            .navigateTo(context, Routes.shopCategory,
                                routeSettings: RouteSettings(arguments: map))
                            .then((value) {
                          if (value == null) {
                            return;
                          }
                          if (value is List<HaowuProduct>) {
                            if (provide.shopList.length != value.length) {
                              widget.back.call(true);
                            }
                          }
                          provide.setShop(value);
                        });
                      },
                    )
                  ],
                ),
              )
      ],
    );
  }

  Widget _shopItem(RelatedShopModel provide, int index, BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: index == 0 ? 0 : ScreenUtil().setHeight(10)),
      height: ScreenUtil().setHeight(110),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
              margin: EdgeInsets.only(right: 12),
              child: Image.network(
                provide.shopList != null
                    ? "${OssHelper.pictureBaseUrl}${provide.shopList[index].picture}"
                    : "",
                width: ScreenUtil().setWidth(80),
                height: ScreenUtil().setWidth(80),
              )),
          Expanded(
              child: Column(
            children: [
              Expanded(
                  child: Container(
                alignment: Alignment.topLeft,
                child: Text(
                    provide.shopList != null &&
                            provide.shopList[index] != null &&
                            provide.shopList[index].productName != null
                        ? provide.shopList[index].productName
                        : "无",
                    maxLines: 2,
                    style: TextStyle(
                        fontSize: ScreenUtil().setSp(16),
                        color: ColorsConfig.c_2c2c2c)),
              )),
              Container(
                  child: Row(
                children: [
                  Text("￥",
                      style: TextStyle(
                          color: ColorsConfig.c_cd0000,
                          fontSize: ScreenUtil().setSp(12))),
                  Expanded(
                      child: Text(
                          provide.shopList != null &&
                                  provide.shopList[index] != null &&
                                  provide.shopList[index].priceData != null &&
                                  provide.shopList[index].priceData.price !=
                                      null
                              ? provide.shopList[index].priceData.price
                                  .toString()
                              : "0.0",
                          style: TextStyle(
                              color: ColorsConfig.c_cd0000,
                              fontSize: ScreenUtil().setSp(16)))),
                ],
              ))
            ],
          )),
          InkWell(
              onTap: () {
                showDialog(
                    context: context,
                    barrierDismissible: false,
                    builder: (_) {
                      return CommTipDialog(
                        content: '确认删除此关联商品？',
                        confirmText: "确认",
                        confirmCallback: () {
                          ZhugeCircleAnalysis.circleDelGoods("编辑动态");
                          widget.setFocus();
                          widget.circle.products.removeAt(index);
                          provide.deleteItem(index);
                          widget.back.call(true);
                        },
                        dismissCallback: () {},
                      );
                    });
              },
              child: Image.asset('picture/icon_delete.png',
                  width: ScreenUtil().setWidth(24),
                  package: 'amway_superapp_creator_plugin',
                  height: ScreenUtil().setWidth(24)))
        ],
      ),
    );
  }
}
